import json

from playwright.sync_api import Browser, Request, Response

from oxk.okx import login_okx, do_oxk_page
from secware.doplus import is_valid_token, write_credentials_to_file, doplus_task


def create_on_response(num):
    # 监听响应
    def on_response(response: Response):
        # print(f'Response {response.status}: {response.url}')
        if '/api/v1/auth/login' in response.url and response.status == 200:
            try:
                print(f'浏览器:{num},抓取token:{response.json()}')
                # 提取 result 字段的内容
                result = response.json().get("result", {})
                # 输出 result 字段的内容
                token = result.get("token")
                user_address = result.get("userAddress")
                # 保存token
                write_credentials_to_file(num, user_address, token)
            except json.JSONDecodeError:
                print("Error decoding JSON response")

    return on_response


# 监听请求
def on_request(request: Request):
    # print(f'Request {request.method} {request.url} ')
    pass


def create_load_handler(num):
    def handle_page_load(page):
        # 页面加载完成后，这里可以进行你的操作
        print(f"页面加载完成:{page.title()}  {page.url}")
        # 执行 okx 页面功能
        do_oxk_page(page, num)

    return handle_page_load


# 新页面创建时，设置load事件监听器
def create_page_handler(num):
    def handle_page_event(page):
        page.on('load', create_load_handler(num))

    return handle_page_event


def intercept_and_click_element(page):
    xpath_expression = "//div[@class='connect hover']/span[text()='Connect Wallet to Scan Risks']"
    # 检查元素是否存在并点击
    try:
        # 等待元素变得可交互
        element = page.wait_for_selector(xpath_expression, state='visible', timeout=5000)
        if element.is_visible():
            element.click()
            print("找到文本为'Connect Wallet to Scan Risks'的元素并点击成功。")
            # 等待一段时间，以等待页面加载完成
            page.wait_for_timeout(5000)
            try:
                if page.locator(
                        ".captcha-solver[data-captcha-type='geetest_v4'] >> text='使用2Captcha解决'").count() > 0:
                    solver_info_element = page.wait_for_selector(".captcha-solver-info", state="visible")
                    if solver_info_element.text_content() == "使用2Captcha解决":
                        # 点击 使用2Captcha解决 会扣费 !!!
                        solver_info_element.click()
                        # page.pause()
                        pass
                    # 判断 元素变成 验证码解决!
                    page.wait_for_function("""
                            () => {
                                const element = document.querySelector('.captcha-solver-info');
                                return element && element.textContent === '验证码解决!';
                            }
                        """, timeout=(2 * 60 * 1000))
                    print("验证码已解决.")
                else:
                    print("未能找到或点击文本为'使用2Captcha解决'的元素。")
            except Exception as e:
                print(f"未能找到或点击文本为'使用2Captcha解决'的元素: {e}")
            try:
                # 定位并点击关闭按钮
                close_button_locator = page.locator(".geetest_close")
                close_button_locator.click()
                page.wait_for_timeout(2000)
            except Exception as e:
                print(f"未能找到或点击关闭弹框的元素: {e}")
            try:
                # 点击MetaMask
                page.locator('.operations div:has(span:text("MetaMask"))').click()
            except Exception as e:
                print(f"点击MetaMask时出错: {e}")
        else:
            print("元素存在但不可见。")
    except Exception as e:
        print(f"未能找到或点击文本为'Connect Wallet to Scan Risks'的元素: {e}")


def secware_login(page, num):
    print(f"浏览器 {num} secware_login: {page.url}")
    # 判断以前的token 是否能使用
    if is_valid_token(num):
        print("token有效,无需重复登录")
    else:
        # 登录处理
        print("token过期,需要登录")
        intercept_and_click_element(page)


def do_task(browser: Browser, num):
    print('开始执行任务,浏览器{}'.format(num))
    context = browser.contexts[0]
    # 注册事件监听器
    context.on('page', create_page_handler(num))
    context.on('response', create_on_response(num))
    context.on('request', on_request)
    # 解锁钱包
    login_okx(context, num)
    # 访问 secwarex
    page = context.pages[0]
    page.goto("https://secwarex.io/?channelCode=KKZMCKDY")
    page.wait_for_timeout(2000)
    # 激活选项卡
    page.bring_to_front()
    # 判断是否需要登录
    secware_login(page, num)
    # 执行任务
    doplus_task(num)
    # 等待页面加载完成
    page.wait_for_timeout(15000)
    # 永久等待
    # page.wait_for_function("() => window.x > 0", timeout=0)
    print('执行任务完成')
